﻿
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using KDS.Mes.Mes.Colors.Dtos;
using KDS.Mes.Dto;
using KDS.Mes.Authorization;
using Abp.UI;

namespace KDS.Mes.Mes.Colors
{
    /// <summary>
    /// 颜色信息服务实现
    /// </summary>
    [AbpAuthorize(AppPermissions.Pages_Bom_Colors)]
    public class ColorAppService : MesAppServiceBase, IColorAppService
    {
        private readonly IRepository<Color, int> _colorRepository;
        private readonly IColorListExcelExporter _colorListExcelExporter;


        private readonly ColorManage _colorManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public ColorAppService(IRepository<Color, int> colorRepository,
ColorManage colorManage
      , IColorListExcelExporter colorListExcelExporter
  )
        {
            _colorRepository = colorRepository;
            _colorManage = colorManage;
            _colorListExcelExporter = colorListExcelExporter;
        }

        #region 颜色信息管理

        public PagedResultDto<ColorListDto> GetPagedColors(GetColorInput input)
        {
            //初步过滤
            var query = _colorRepository.GetAll();
            //排序
            query = !string.IsNullOrEmpty(input.Sorting) ? query.OrderBy(x => x.Id) : query.OrderByDescending(t => t.CreationTime);
            //获取总数
            var tasksCount = query.Count();
            //默认的分页方式
            //var taskList = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            //ABP提供了扩展方法PageBy分页方式
            var taskList = query.PageBy(input).ToList();
            return new PagedResultDto<ColorListDto>(tasksCount, taskList.MapTo<List<ColorListDto>>());
        }


        /// <summary>
        /// 根据查询条件获取颜色信息分页列表
        /// </summary>
        public async Task<PagedResultDto<ColorListDto>> GetPagedColorsAsync(GetColorInput input)
        {

            var query = _colorRepository.GetAll();
            //TODO:根据传入的参数添加过滤条件

            var colorCount = await query.CountAsync();

            var colors = await query
            .OrderBy(input.Sorting)
            .PageBy(input)
            .ToListAsync();

            var colorListDtos = colors.MapTo<List<ColorListDto>>();
            return new PagedResultDto<ColorListDto>(
            colorCount,
            colorListDtos
            );
        }

        /// <summary>
        /// 通过Id获取颜色信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetColorForEditOutput> GetColorForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetColorForEditOutput();

            ColorEditDto colorEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _colorRepository.GetAsync(input.Id.Value);
                colorEditDto = entity.MapTo<ColorEditDto>();
            }
            else
            {
                colorEditDto = new ColorEditDto();
            }

            output.Color = colorEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取颜色信息ListDto信息
        /// </summary>
        public async Task<ColorListDto> GetColorByIdAsync(EntityDto<int> input)
        {
            var entity = await _colorRepository.GetAsync(input.Id);

            return entity.MapTo<ColorListDto>();
        }







        /// <summary>
        /// 新增或更改颜色信息
        /// </summary>
        public async Task CreateOrUpdateColorAsync(CreateOrUpdateColorInput input)
        {
            if (input.ColorEditDto.Id.HasValue)
            {
                await UpdateColorAsync(input.ColorEditDto);
            }
            else
            {
                await CreateColorAsync(input.ColorEditDto);
            }
        }

        /// <summary>
        /// 新增颜色信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Colors_Create)]
        public virtual async Task<ColorEditDto> CreateColorAsync(ColorEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            await CheckColorIfAlreadyExists(input);
            var entity = input.MapTo<Color>();

            entity = await _colorRepository.InsertAsync(entity);
            return entity.MapTo<ColorEditDto>();
        }

        /// <summary>
        /// 编辑颜色信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Colors_Edit)]
        public virtual async Task UpdateColorAsync(ColorEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            await CheckColorIfAlreadyExists(input);
            var entity = await _colorRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _colorRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除颜色信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Colors_Delete)]
        public async Task DeleteColorAsync(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _colorRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除颜色信息
        /// </summary>
        [AbpAuthorize(AppPermissions.Pages_Bom_Colors_Delete)]
        public async Task BatchDeleteColorAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _colorRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        private async Task CheckColorIfAlreadyExists(ColorEditDto input)
        {
            var existingColor = await _colorRepository.GetAll()
                .FirstOrDefaultAsync(l => l.ColorName == input.ColorName || l.ColorCode == input.ColorCode);
            if (existingColor == null)
            {
                return;
            }
            if (input.Id != null && existingColor.Id == input.Id)
            {
                return;
            }
            throw new UserFriendlyException(L("ThisColorAlreadyExists"));
        }

        #endregion


        #region 颜色信息的Excel导出功能


        public async Task<FileDto> GetColorToExcel()
        {
            var entities = await _colorRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<ColorListDto>>();

            var fileDto = _colorListExcelExporter.ExportColorToFile(dtos);



            return fileDto;
        }


        #endregion










    }
}
